package org.xin.common.result;

import cn.hutool.core.date.DateUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.xin.common.util.XinUtil;

/**
 * @author ：xin
 * @date ：Created in 2021/9/29
 * @desc <p>  </p>
 * @modified By：$
 * @version: $
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    private static final long serialVersionUID = 1L;

    /**
     * 成功标志
     */
    private boolean success;

    /**
     * 返回处理消息
     */
    private CharSequence message;

    /**
     * 返回代码
     */
    private Integer code;

    /**
     * 返回数据对象 data
     */
    private Object data;

    /**
     * 时间戳
     */
    private String timestamp = DateUtil.now();


    public static Result ok(){
        return result(ResultCode.SUCCESS, null, null, null, false);
    }

    public static Result check(boolean result){
        return result ? ok() : error("操作失败");
    }

    public static Result ok(CharSequence msg){
        return result(ResultCode.SUCCESS, null, msg, null, false);
    }

    public Result ok(String msg, Object data){
        return result(ResultCode.SUCCESS, data, msg, null, false);
    }

    public static Result success(Object data){
        return result(ResultCode.SUCCESS, data, null, null, false);
    }



    public static Result success(Object data, CharSequence msg){
        return result(ResultCode.SUCCESS, data, msg, null, false);
    }
    public static Result error(CharSequence msg){
        return result(ResultCode.FAILURE, null, msg, null, false);
    }

    public static Result error(ResultCode resultCode){
        return result(resultCode, null, null, null, false);
    }

    public static Result error(ResultCode resultCode, CharSequence msg){
        return result(resultCode, null, msg, null, false);
    }

    public static Result error(int code, CharSequence msg){
        return result(ResultCode.FAILURE, null, msg, code, false);
    }


    private static Result result(ResultCode resultCode, Object data, CharSequence msg, Integer code, Boolean show) {
        Result result = Result.builder()
                .success(resultCode.getCode() == 200)
                .message(resultCode.getDesc())
                .code(resultCode.getCode()).build();
        if (XinUtil.noNull(code)) {
            result.setCode(code);
        }
        if (XinUtil.noNull(data)) {
            result.setData(data);
        }
        if (XinUtil.noNull(msg)) {
            result.setMessage(msg);
        }
        return result;
    }
}
